import React from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  message,
  Popconfirm,
  Select,
  Table,
  Tooltip,
  DatePicker,
} from 'antd';

import SearchForm from '../../components/AutoForm/SearchForm';
import { connect } from 'dva';
import moment from 'moment';
import EditForm from '../../components/AutoForm/EditForm';
import PicturesWall from "../../components/FileUpload/PicturesWall";
import { imgServerServer } from "../../utils/Constant";

const { Option } = Select;
const { TextArea } = Input;

const EditableContext = React.createContext();

@connect(({ fixedAssets, customer }) => ({
  requiredCols: fixedAssets.requiredCols,
}))
class EditableCell extends React.Component {
  getInput = (dataIndex, record) => {
    switch (dataIndex) {
      case 'type':
        return (
          <Select style={{ width: 100 }}>
            <Option value={0}>固定资产</Option>
            <Option value={1}>耗材资产</Option>
          </Select>
        );
      case 'amount':
        return <Input type="number" />;
      case 'buyPrice':
        return <Input type="number" />;
      case 'buyTime':
        return <DatePicker showTime />;
      default:
        return <Input />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      selectData,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue:
                dataIndex === 'buyTime'
                  ? record[dataIndex]
                    ? moment(record[dataIndex])
                    : moment()
                  : record[dataIndex],
            })(this.getInput(dataIndex, record, selectData))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ fixedAssets, loading, fileUp }) => ({
  tableLoading: loading.effects['fixedAssets/page'],
  logLoading: loading.effects['fixedAssets/log','fixedAssets/imgs'],
  tableData: fixedAssets.pageList,
  pagination: fixedAssets.pagination,
  columns: fixedAssets.columns,
  columnsLog: fixedAssets.columnsLog,
  searchFields: fixedAssets.searchFields,
  searchValues: fixedAssets.searchValues,
  editId: fixedAssets.editId,
  selectionIds: fixedAssets.selectionIds,
  selectedRows: fixedAssets.selectedRows,
  tmsUserList: fixedAssets.tmsUserList,
  assets: fileUp.assets,
}))
class EditableTable extends React.Component {
  state = {
    modalTitle: '',
    logForm: {},
    modalVisible: false,
    amount: 0,
    assetVersion: 0,
    assetAmount: 0,
    imgModalId: 0,
    imgModalTitle: '',
    imgForm: {},
    imgModalVisible: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.handleSearch();
    dispatch({
      type: 'fixedAssets/selectUserList',
    });
  }

  expandedRowRender = record => {
    const { columnsLog } = this.props;

    return <Table size="small" columns={columnsLog} dataSource={record.logs} pagination={false} />;
  };

  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fixedAssets/handleEdit',
      payload: '',
    });
  };

  save(form, id, version) {
    const { dispatch } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      row.comfirmTime = moment(row.comfirmTime).add(8, 'h');
      row.buyTime = moment(row.buyTime).add(8, 'h');

      dispatch({
        type: 'fixedAssets/save',
        payload: { ...row, id, version },
      }).then(() => {
        this.handleSearch();
      });
    });
  }

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'fixedAssets/handleEdit',
      payload: key,
    });
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fixedAssets/handleSearchChange',
      payload: fields,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fixedAssets/handleAdd',
    });
  };

  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'fixedAssets/page',
      payload: param,
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fixedAssets/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onDel = () => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行要删除的数据');
    }
    dispatch({
      type: 'fixedAssets/del',
      payload: selectedRows[0],
    }).then(() => {
      this.handleSearch();
    });
  };

  onSwap = () => {
    const { selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行要移交的数据');
    }

    if (selectedRows[0]['type'] === 1) {
      return message.error('耗材不能移交');
    }
    this.setState({
      logForm: [],
      modalVisible: 'true',
      modalTitle: `移交资产： ${selectedRows[0].name} 当前数量： ${selectedRows[0].amount}`,
    });
  };

  onInbox = () => {
    debugger;
    const { selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行要移交的数据');
    }

    if (selectedRows[0]['type'] === 0) {
      return message.error('固定资产不能领用');
    }

    let amount = selectedRows[0].amount;
    if (selectedRows[0].logs.length) {
      amount = selectedRows[0].logs[0].surplusAmount;
    }
    this.setState({
      logForm: [],
      modalVisible: 'true',
      modalTitle: `领用资产： ${selectedRows[0].name} 当前数量： ${selectedRows[0].amount}`,
      amount: amount,
    });
  };

  handleLogChange = fields => {
    const { logForm, amount } = this.state;
    if (fields['changeAmount']) {
      let surplusAmount = (amount - fields.changeAmount.value).toFixed(2);
      if (surplusAmount < 0.0) {
        return message.error('领用数量超出');
      }
      fields = {
        ...fields,
        surplusAmount: {
          name: 'surplusAmount',
          value: surplusAmount,
        },
      };
    }
    this.setState({
      logForm: {
        ...logForm,
        ...fields,
      },
    });
  };

  handleImgChange = fields => {
    const { imgForm } = this.state
    this.setState({
      imgForm: {
        ...imgForm,
        ...fields,
      },
    });
  }

  handleVisible = () => {
    this.setState({
      modalVisible: false,
      imgModalVisible: false,
    });
  };

  handleLogSub = fields => {
    const { dispatch, selectedRows, tmsUserList } = this.props;
    fields.fixedAssetsId = selectedRows[0].id;
    fields.version = selectedRows[0].version;
    fields.changeTime = moment(fields.changeTime).add(8, 'h');

    tmsUserList.forEach(tmsUser => {
      if (tmsUser.code === fields.changeUser) {
        fields.changeUserName = tmsUser.label;
      }
    });
    dispatch({
      type: 'fixedAssets/logs',
      payload: fields,
    }).then(() => {
      this.handleSearch();
      this.handleVisible();
    });
  };
  handleImgSub = fields => {
    const { dispatch, assets } = this.props;
    const { imgModalId, assetVersion, assetAmount } = this.state;
    let imgUrls = [];
    assets.forEach(asset => {
      if(asset.status === 'done'){
        let img = asset.url || asset.response.result
        img = img.replace(imgServerServer, '');
        imgUrls.push(img);
      }
    })
    const param = {
      id: imgModalId,
      version: assetVersion,
      amount: assetAmount,
      okImg: imgUrls.join(";")
    }
    dispatch({
      type: 'fixedAssets/imgs',
      payload: param,
    }).then(()=>{
      this.handleVisible();
      this.handleSearch()
    })
  };

  handleImage = record => {
    const { dispatch } = this.props
    let fileList = []
    if(record.okImg) {
      const imgs = record.okImg.split(";")
      imgs.forEach((img, index) => {
        const file = {
          uid: record.id + index,
          url: imgServerServer + img,
          status: 'done'
        }
        fileList.push(file);
      })
    }
    dispatch({
      type: 'fileUp/assetsChange',
      payload: fileList
    })
    this.setState({
      imgModalId: record.id,
      assetVersion: record.version,
      imgModalVisible: true,
      assetAmount: record.amount,
      imgModalTitle: `${record.name}`
    })
  }

  render() {
    const {
      columns,
      pagination,
      tableLoading,
      logLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch,
      tmsUserList,
    } = this.props;
    const { modalTitle } = this.state;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const logRows = [
      {
        cols: [
          {
            label: '变动人员',
            name: 'changeUser',
            md: 12,
            rules: [{ required: true, message: ' ' }],
            component: (
              <Select
                showSearch
                placeholder={'请选择变动人员'}
                filterOption={(input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
              >
                {tmsUserList.map(tmsUser => {
                  return <Option value={tmsUser.code}>{tmsUser.label}</Option>;
                })}
              </Select>
            ),
          },
          {
            label: '变动时间',
            name: 'changeTime',
            md: 12,
            rules: [{ required: true, message: ' ' }],
            component: <DatePicker showTime={true} format="YYYY-MM-DD HH:mm:ss" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '变动数量',
            name: 'changeAmount',
            md: 12,
            rules: [
              {
                required: this.props.selectedRows[0] && this.props.selectedRows[0].type === 1,
                message: ' ',
              },
            ],
            component: (
              <Input
                disabled={!this.props.selectedRows[0] || this.props.selectedRows[0].type === 0}
                type={'number'}
              />
            ),
          },
        ],
      },
      {
        cols: [
          {
            label: '剩余数量',
            name: 'surplusAmount',
            md: 12,
            component: (
              <Input
                onChange={this.amountChange}
                disabled={!this.props.selectedRows[0] || this.props.selectedRows[0].type === 0}
                readOnly={true}
                type={'number'}
              />
            ),
          },
        ],
      },
      {
        cols: [
          {
            label: '备注',
            name: 'remark',
            md: 12,
            component: <TextArea placeholder={'请输入备注'} />,
          },
        ],
      },
    ];

    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });
    optColumns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <Tooltip placement="bottom" title="保存">
                  <Button
                    size="small"
                    onClick={() => this.save(form, record.id, record.version)}
                    icon="save"
                  />
                </Tooltip>
              )}
            </EditableContext.Consumer>
            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.id)}
            >
              <Tooltip placement="bottom" title="撤回">
                <Button size="small" icon="rollback" />
              </Tooltip>
            </Popconfirm>
          </span>
        ) : (
          <div>
          <Tooltip placement="bottom" title="编辑">
            <Button size="small" icon="edit" onClick={() => this.handleEdit(record.id)} />
          </Tooltip>
          <Tooltip placement="bottom" title="资产照片">
            <Button size="small" icon='picture' onClick={() => this.handleImage(record)} />
          </Tooltip>
          </div>
        );
      },
    });

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'fixedAssets/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'fixedAssets/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
    };

    let imgFormRows = [
      {
        cols: [
          {
            label: '资产照片',
            name: 'okImg',
            md: 12,
            component: (
              <PicturesWall type={"assets"} fileSize={2} />
            ),
          }
        ]
      }
    ];

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="固定资产->操作"
          layout="infixedAssets"
          isAdd={true}
          isDel={true}
          isSwap={true}
          onSwap={this.onSwap}
          isInBox={true}
          onInBox={this.onInbox}
          onFieldsChange={this.handleSearchChange}
          onAdd={this.handleAdd}
          onSubmit={() => {this.handleSearch('btn')}}
          onDel={this.onDel}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            rowKey="id"
            loading={tableLoading}
            dataSource={tableData}
            columns={optColumns}
            rowSelection={rowSelection}
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={pagination}
            expandedRowRender={this.expandedRowRender}
          />
        </EditableContext.Provider>
        <EditForm
          title={modalTitle}
          rows={logRows}
          fieldValue={this.state.logForm}
          onFieldsChange={this.handleLogChange}
          onCancel={this.handleVisible}
          confirmLoading={logLoading}
          onOk={this.handleLogSub}
          visible={this.state.modalVisible}
        />
        <EditForm
          title={this.state.imgModalTitle}
          rows={imgFormRows}
          fieldValue={this.state.imgForm}
          onFieldsChange={this.handleImgChange}
          onCancel={this.handleVisible}
          confirmLoading={logLoading}
          onOk={this.handleImgSub}
          visible={this.state.imgModalVisible}
        />
      </Card>
    );
  }
}
const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
